class Game {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.gameState = 'menu'; // menu, playing, gameOver
        this.score = 0;
        this.ultraman = null;
        this.zombies = [];
        this.beams = [];
        this.tombstones = [];
        this.fireballs = [];
        this.iceballs = [];
        this.crystals = []; // 水晶数组
        this.zombiesKilled = 0; // 击败的僵尸数量
        this.zombieCannons = []; // 僵尸大炮数组
        this.keys = {};
        this.lastTime = 0;
        
        this.init();
    }
    
    init() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        
        // 事件监听
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('restartBtn').addEventListener('click', () => this.restartGame());
        
        document.addEventListener('keydown', (e) => {
            this.keys[e.key.toLowerCase()] = true;
        });
        
        document.addEventListener('keyup', (e) => {
            this.keys[e.key.toLowerCase()] = false;
        });
    }
    
    startGame() {
        this.gameState = 'playing';
        document.getElementById('gameTitle').style.display = 'none';
        document.getElementById('gameArea').style.display = 'block';
        
        // 初始化游戏对象
        this.ultraman = new Ultraman(100, 400);
        this.zombies = [];
        this.beams = [];
        this.tombstones = [];
        this.fireballs = [];
        this.iceballs = [];
        this.crystals = [];
        this.zombiesKilled = 0;
        this.zombieCannons = [];
        this.score = 0;
        
        // 生成一些固定的墓碑作为地图障碍物
        this.generateMapTombstones();
        
        // 生成3个僵尸大炮
        this.generateZombieCannons();
        
        this.gameLoop();
    }
    
    restartGame() {
        document.getElementById('gameOver').style.display = 'none';
        const winScreen = document.getElementById('gameWin');
        if (winScreen) {
            winScreen.style.display = 'none';
        }
        this.startGame();
    }
    
    gameLoop(currentTime = 0) {
        if (this.gameState !== 'playing') return;
        
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        this.update(deltaTime);
        this.render();
        
        requestAnimationFrame((time) => this.gameLoop(time));
    }
    
    update(deltaTime) {
        // 更新奥特曼
        this.ultraman.update(deltaTime, this.keys);
        
        // 更新僵尸大炮
        this.zombieCannons.forEach(cannon => {
            cannon.update(deltaTime, this);
        });
        
        // 更新僵尸
        this.zombies.forEach(zombie => {
            zombie.update(deltaTime, this.ultraman);
        });
        
        // 更新光线
        this.beams.forEach(beam => beam.update(deltaTime));
        
        // 更新墓碑
        this.tombstones.forEach(tombstone => tombstone.update(deltaTime));
        
        // 更新火球和冰球
        this.fireballs.forEach(fireball => fireball.update(deltaTime));
        this.iceballs.forEach(iceball => iceball.update(deltaTime));
        
        // 更新水晶
        this.crystals.forEach(crystal => crystal.update(deltaTime));
        
        // 碰撞检测
        this.checkCollisions();
        
        // 清理超出屏幕的对象
        this.cleanup();
        
        // 更新UI
        this.updateUI();
        
        // 检查游戏结束
        if (this.ultraman.health <= 0) {
            this.gameOver();
        }
        
        // 检查游戏胜利（所有僵尸大炮被摧毁）
        if (this.zombieCannons.length === 0 && this.zombies.length === 0) {
            this.gameWin();
        }
    }
    
    spawnZombie() {
        const x = this.canvas.width + 50;
        const y = Math.random() * (this.canvas.height - 100) + 50;
        this.zombies.push(new Zombie(x, y));
    }
    
    generateMapTombstones() {
        // 在地图中生成一些固定的墓碑作为障碍物
        const tombstonePositions = [
            {x: 300, y: 200},
            {x: 500, y: 350},
            {x: 700, y: 150},
            {x: 900, y: 400},
            {x: 400, y: 450}
        ];
        
        tombstonePositions.forEach(pos => {
            const tombstone = new Tombstone(pos.x, pos.y);
            tombstone.isMapTombstone = true; // 标记为地图墓碑
            this.tombstones.push(tombstone);
        });
    }
    
    checkCollisions() {
        // 奥特曼光线 vs 僵尸
        this.beams.forEach((beam, beamIndex) => {
            this.zombies.forEach((zombie, zombieIndex) => {
                if (this.isColliding(beam, zombie)) {
                    zombie.takeDamage(beam.damage);
                    this.beams.splice(beamIndex, 1);
                    
                    if (zombie.health <= 0) {
                        this.score += zombie.points;
                        this.zombiesKilled++;
                        this.zombies.splice(zombieIndex, 1);
                        
                        // 每击败3个僵尸生成一个水晶
                        if (this.zombiesKilled % 3 === 0) {
                            this.spawnCrystal(zombie.x, zombie.y);
                        }
                    }
                }
            });
            
            // 光线 vs 墓碑
            this.tombstones.forEach((tombstone, tombstoneIndex) => {
                if (this.isColliding(beam, tombstone)) {
                    tombstone.takeDamage(beam.damage);
                    this.beams.splice(beamIndex, 1);
                    
                    if (tombstone.health <= 0) {
                        this.tombstones.splice(tombstoneIndex, 1);
                    }
                }
            });
            
            // 光线 vs 僵尸大炮
            this.zombieCannons.forEach((cannon, cannonIndex) => {
                if (this.isColliding(beam, cannon)) {
                    cannon.takeDamage(beam.damage);
                    this.beams.splice(beamIndex, 1);
                    
                    if (cannon.health <= 0) {
                        this.score += cannon.points;
                        this.zombieCannons.splice(cannonIndex, 1);
                    }
                }
            });
        });
        
        // 奥特曼 vs 僵尸 (近战攻击)
        if (this.ultraman.isAttacking) {
            const meleeDamage = this.ultraman.currentMeleeDamage || this.ultraman.meleeDamage;
            
            this.zombies.forEach((zombie, zombieIndex) => {
                if (this.isColliding(this.ultraman, zombie)) {
                    zombie.takeDamage(meleeDamage);
                    
                    // 连击特效：击退效果
                    if (this.ultraman.comboCount >= 2) {
                        const knockbackForce = 100 * this.ultraman.comboCount;
                        const dx = zombie.x - this.ultraman.x;
                        const dy = zombie.y - this.ultraman.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        if (distance > 0) {
                            zombie.x += (dx / distance) * knockbackForce * 0.016;
                            zombie.y += (dy / distance) * knockbackForce * 0.016;
                        }
                    }
                    
                    if (zombie.health <= 0) {
                        this.score += zombie.points * this.ultraman.comboCount;
                        this.zombiesKilled++;
                        this.zombies.splice(zombieIndex, 1);
                        
                        // 每击败3个僵尸生成一个水晶
                        if (this.zombiesKilled % 3 === 0) {
                            this.spawnCrystal(zombie.x, zombie.y);
                        }
                    }
                }
            });
            
            // 奥特曼 vs 僵尸大炮 (近战攻击)
            this.zombieCannons.forEach((cannon, cannonIndex) => {
                if (this.isColliding(this.ultraman, cannon)) {
                    cannon.takeDamage(meleeDamage);
                    
                    if (cannon.health <= 0) {
                        this.score += cannon.points * this.ultraman.comboCount;
                        this.zombieCannons.splice(cannonIndex, 1);
                    }
                }
            });
        }
        
        // 火球 vs 奥特曼
        this.fireballs.forEach((fireball, index) => {
            if (this.isColliding(fireball, this.ultraman)) {
                this.ultraman.takeDamage(fireball.damage);
                this.ultraman.applyBurn();
                this.fireballs.splice(index, 1);
            }
        });
        
        // 冰球 vs 奥特曼
        this.iceballs.forEach((iceball, index) => {
            if (this.isColliding(iceball, this.ultraman)) {
                this.ultraman.takeDamage(iceball.damage);
                this.ultraman.applyFreeze();
                this.iceballs.splice(index, 1);
            }
        });
        
        // 奥特曼光线 vs 水晶
        this.beams.forEach((beam, beamIndex) => {
            this.crystals.forEach((crystal, crystalIndex) => {
                if (this.isColliding(beam, crystal)) {
                    this.ultraman.activateOmniShot(); // 激活四面八方射击
                    this.ultraman.addEnergy(30); // 增加30点能量
                    this.beams.splice(beamIndex, 1);
                    this.crystals.splice(crystalIndex, 1);
                }
            });
        });
        
        // 僵尸 vs 奥特曼 (近战)
        this.zombies.forEach(zombie => {
            if (this.isColliding(zombie, this.ultraman) && zombie.canAttack()) {
                this.ultraman.takeDamage(zombie.damage);
                zombie.lastAttackTime = Date.now();
            }
        });
    }
    
    isColliding(obj1, obj2) {
        return obj1.x < obj2.x + obj2.width &&
               obj1.x + obj1.width > obj2.x &&
               obj1.y < obj2.y + obj2.height &&
               obj1.y + obj1.height > obj2.y;
    }
    
    cleanup() {
        // 清理超出屏幕的对象
        this.beams = this.beams.filter(beam => 
            beam.x > -100 && beam.x < this.canvas.width + 100 && 
            beam.y > -100 && beam.y < this.canvas.height + 100
        );
        this.zombies = this.zombies.filter(zombie => zombie.x > -100);
        // 只清理非地图墓碑
        this.tombstones = this.tombstones.filter(tombstone => 
            tombstone.isMapTombstone || tombstone.x > -100
        );
        this.fireballs = this.fireballs.filter(fireball => fireball.x > -100);
        this.iceballs = this.iceballs.filter(iceball => iceball.x > -100);
        this.crystals = this.crystals.filter(crystal => crystal.x > -100 && crystal.x < this.canvas.width + 100);
        this.zombieCannons = this.zombieCannons.filter(cannon => cannon.x > -100);
    }
    
    updateUI() {
        document.getElementById('scoreValue').textContent = this.score;
        document.getElementById('healthValue').textContent = Math.max(0, this.ultraman.health);
        document.getElementById('energyValue').textContent = Math.max(0, this.ultraman.energy);
        
        // 显示击败僵尸数量和四面八方射击状态
        const statusElement = document.getElementById('gameStatus');
        if (!statusElement) {
            const newStatusElement = document.createElement('div');
            newStatusElement.id = 'gameStatus';
            newStatusElement.style.position = 'absolute';
            newStatusElement.style.top = '120px';
            newStatusElement.style.left = '20px';
            newStatusElement.style.color = 'white';
            newStatusElement.style.fontSize = '16px';
            newStatusElement.style.fontFamily = 'Arial, sans-serif';
            document.getElementById('gameArea').appendChild(newStatusElement);
        }
        
        const statusEl = document.getElementById('gameStatus');
        let statusText = `击败僵尸: ${this.zombiesKilled}`;
        statusText += `\n僵尸大炮: ${this.zombieCannons.length}`;
        if (this.ultraman.comboCount > 1 && this.ultraman.comboTimer > 0) {
            statusText += `\n连击: ${this.ultraman.comboCount}x`;
        }
        if (this.ultraman.omniShotActive) {
            const remainingTime = Math.ceil(this.ultraman.omniShotTimer / 1000);
            statusText += `\n四面八方射击: ${remainingTime}秒`;
        }
        statusEl.innerHTML = statusText.replace(/\n/g, '<br>');
    }
    
    gameOver() {
        this.gameState = 'gameOver';
        document.getElementById('gameArea').style.display = 'none';
        document.getElementById('gameOver').style.display = 'block';
        document.getElementById('finalScore').textContent = this.score;
    }
    
    gameWin() {
        this.gameState = 'gameWin';
        // 创建胜利界面
        let winScreen = document.getElementById('gameWin');
        if (!winScreen) {
            winScreen = document.createElement('div');
            winScreen.id = 'gameWin';
            winScreen.style.position = 'absolute';
            winScreen.style.top = '50%';
            winScreen.style.left = '50%';
            winScreen.style.transform = 'translate(-50%, -50%)';
            winScreen.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            winScreen.style.color = 'gold';
            winScreen.style.padding = '40px';
            winScreen.style.borderRadius = '10px';
            winScreen.style.textAlign = 'center';
            winScreen.style.fontSize = '24px';
            winScreen.style.fontFamily = 'Arial, sans-serif';
            winScreen.innerHTML = `
                <h2>🎉 胜利！🎉</h2>
                <p>你成功摧毁了所有僵尸大炮！</p>
                <p>最终得分: <span id="winScore">${this.score}</span></p>
                <button onclick="game.restartGame()" style="padding: 10px 20px; font-size: 16px; margin-top: 20px;">再玩一次</button>
            `;
            document.getElementById('gameArea').appendChild(winScreen);
        } else {
            document.getElementById('winScore').textContent = this.score;
            winScreen.style.display = 'block';
        }
    }
    
    render() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制背景
        this.drawBackground();
        
        // 绘制游戏对象
        this.ultraman.render(this.ctx);
        
        this.zombies.forEach(zombie => zombie.render(this.ctx));
        this.beams.forEach(beam => beam.render(this.ctx));
        this.tombstones.forEach(tombstone => tombstone.render(this.ctx));
        this.fireballs.forEach(fireball => fireball.render(this.ctx));
        this.iceballs.forEach(iceball => iceball.render(this.ctx));
        this.crystals.forEach(crystal => crystal.render(this.ctx));
        this.zombieCannons.forEach(cannon => cannon.render(this.ctx));
    }
    
    drawBackground() {
        // 绘制简单的背景
        const gradient = this.ctx.createLinearGradient(0, 0, 0, this.canvas.height);
        gradient.addColorStop(0, '#87CEEB');
        gradient.addColorStop(0.5, '#98FB98');
        gradient.addColorStop(1, '#8FBC8F');
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制地面
        this.ctx.fillStyle = '#8B4513';
        this.ctx.fillRect(0, this.canvas.height - 50, this.canvas.width, 50);
    }
    
    // 添加投射物的方法
    addBeam(beam) {
        this.beams.push(beam);
    }
    
    addTombstone(tombstone) {
        this.tombstones.push(tombstone);
    }
    
    addFireball(fireball) {
        this.fireballs.push(fireball);
    }
    
    addIceball(iceball) {
        this.iceballs.push(iceball);
    }
    
    spawnCrystal(x, y) {
        const crystal = new Crystal(x, y);
        this.crystals.push(crystal);
    }
    
    addCrystal(crystal) {
        this.crystals.push(crystal);
    }
    
    generateZombieCannons() {
        // 生成3个僵尸大炮，分布在屏幕右侧不同高度
        const cannonPositions = [
            {x: this.canvas.width - 120, y: 150}, // 修改位置到屏幕内
            {x: this.canvas.width - 120, y: 300},
            {x: this.canvas.width - 120, y: 450}
        ];
        
        cannonPositions.forEach(pos => {
            const cannon = new ZombieCannon(pos.x, pos.y);
            this.zombieCannons.push(cannon);
        });
    }
    
    addZombie(zombie) {
        this.zombies.push(zombie);
    }
}

class Ultraman {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 40;
        this.height = 60;
        this.health = 100;
        this.maxHealth = 100;
        this.energy = 100;
        this.maxEnergy = 100;
        this.speed = 200;
        this.jumpPower = 300;
        this.velocityY = 0;
        this.onGround = true;
        this.gravity = 800;
        this.meleeDamage = 50; // 增加近战伤害
        this.beamDamage = 40;
        this.isAttacking = false;
        this.attackCooldown = 0;
        this.meleeRange = 80; // 近战攻击范围
        this.comboCount = 0; // 连击数
        this.maxCombo = 3; // 最大连击数
        this.comboTimer = 0; // 连击计时器
        this.comboWindow = 1000; // 连击窗口时间（毫秒）
        this.beamCooldown = 0;
        this.isBurning = false;
        this.isFrozen = false;
        this.burnTimer = 0;
        this.freezeTimer = 0;
        this.attackPower = 1.0; // 攻击力倍数
        this.omniShotActive = false; // 四面八方射击是否激活
        this.omniShotTimer = 0; // 四面八方射击计时器
        this.omniShotDuration = 10000; // 持续10秒
    }
    
    update(deltaTime, keys) {
        const dt = deltaTime / 1000;
        
        // 处理状态效果
        this.updateStatusEffects(dt);
        
        // 更新四面八方射击状态
        this.updateOmniShot(dt);
        
        // 移动控制
        let moveSpeed = this.speed * (this.isFrozen ? 0.5 : 1.0);
        
        if (keys['a'] && this.x > 0) {
            this.x -= moveSpeed * dt;
        }
        if (keys['d'] && this.x < 1200 - this.width) {
            this.x += moveSpeed * dt;
        }
        if (keys['w'] && this.y > 0) {
            this.y -= moveSpeed * dt;
        }
        if (keys['s'] && this.y < 600 - this.height - 50) {
            this.y += moveSpeed * dt;
        }
        
        // 跳跃
        if (keys[' '] && this.onGround) {
            this.velocityY = -this.jumpPower;
            this.onGround = false;
        }
        
        // 重力
        if (!this.onGround) {
            this.velocityY += this.gravity * dt;
            this.y += this.velocityY * dt;
            
            if (this.y >= 600 - this.height - 50) {
                this.y = 600 - this.height - 50;
                this.velocityY = 0;
                this.onGround = true;
            }
        }
        
        // 攻击控制
        if (this.attackCooldown > 0) {
            this.attackCooldown -= deltaTime;
        }
        
        if (this.beamCooldown > 0) {
            this.beamCooldown -= deltaTime;
        }
        
        // 更新连击计时器
        if (this.comboTimer > 0) {
            this.comboTimer -= deltaTime;
            if (this.comboTimer <= 0) {
                this.comboCount = 0; // 连击窗口结束，重置连击数
            }
        }
        
        if (keys['j'] && this.attackCooldown <= 0) {
            this.meleeAttack();
        }
        
        if (keys['k'] && this.beamCooldown <= 0 && this.energy >= 20) {
            if (this.omniShotActive) {
                this.shootOmniBeam();
            } else {
                this.shootBeam();
            }
        }
        
        // 能量恢复
        if (this.energy < this.maxEnergy) {
            this.energy += 30 * dt;
            this.energy = Math.min(this.energy, this.maxEnergy);
        }
        
        this.isAttacking = false;
    }
    
    updateStatusEffects(dt) {
        // 燃烧效果
        if (this.isBurning) {
            this.burnTimer -= dt;
            this.health -= 5 * dt; // 每秒损失5点生命值
            this.attackPower = 0.7; // 攻击力降低30%
            
            if (this.burnTimer <= 0) {
                this.isBurning = false;
                this.attackPower = 1.0;
            }
        }
        
        // 冰冻效果
        if (this.isFrozen) {
            this.freezeTimer -= dt;
            
            if (this.freezeTimer <= 0) {
                this.isFrozen = false;
            }
        }
    }
    
    meleeAttack() {
        if (this.energy >= 5) { // 降低能量消耗
            this.energy -= 5;
            this.isAttacking = true;
            
            // 连击系统
            this.comboCount++;
            this.comboTimer = this.comboWindow;
            
            if (this.comboCount > this.maxCombo) {
                this.comboCount = this.maxCombo;
            }
            
            // 根据连击数调整冷却时间和伤害
            const comboDamageMultiplier = 1 + (this.comboCount - 1) * 0.5;
            this.currentMeleeDamage = this.meleeDamage * comboDamageMultiplier;
            
            // 连击越高，冷却时间越短
            const cooldownReduction = Math.min(this.comboCount * 50, 200);
            this.attackCooldown = Math.max(300 - cooldownReduction, 100);
            
            // 攻击动画持续时间
            setTimeout(() => {
                this.isAttacking = false;
            }, 150);
        }
    }
    
    shootBeam() {
        const beam = new Beam(this.x + this.width, this.y + this.height / 2, this.beamDamage * this.attackPower);
        game.addBeam(beam);
        this.energy -= 20;
        this.beamCooldown = 300; // 0.3秒冷却
    }
    
    takeDamage(damage) {
        this.health -= damage;
        this.health = Math.max(0, this.health);
    }
    
    applyBurn() {
        this.isBurning = true;
        this.burnTimer = 5; // 燃烧5秒
    }
    
    applyFreeze() {
        this.isFrozen = true;
        this.freezeTimer = 3; // 冰冻3秒
    }
    
    updateOmniShot(dt) {
        if (this.omniShotActive) {
            this.omniShotTimer -= dt * 1000;
            if (this.omniShotTimer <= 0) {
                this.omniShotActive = false;
            }
        }
    }
    
    activateOmniShot() {
        this.omniShotActive = true;
        this.omniShotTimer = this.omniShotDuration;
    }
    
    shootOmniBeam() {
        // 向8个方向发射光线
        const directions = [
            {x: 1, y: 0},    // 右
            {x: -1, y: 0},   // 左
            {x: 0, y: -1},   // 上
            {x: 0, y: 1},    // 下
            {x: 1, y: -1},   // 右上
            {x: 1, y: 1},    // 右下
            {x: -1, y: -1},  // 左上
            {x: -1, y: 1}    // 左下
        ];
        
        directions.forEach(dir => {
            const beam = new Beam(
                this.x + this.width / 2, 
                this.y + this.height / 2, 
                this.beamDamage * this.attackPower,
                dir.x,
                dir.y
            );
            game.addBeam(beam);
        });
        
        this.energy -= 20;
        this.beamCooldown = 300;
    }
    
    addEnergy(amount) {
        this.energy += amount;
        this.energy = Math.min(this.energy, this.maxEnergy);
    }
    
    render(ctx) {
        // 绘制奥特曼
        let baseColor = '#ff6b6b';
        if (this.isBurning) {
            baseColor = '#ff4444';
        } else if (this.isFrozen) {
            baseColor = '#4444ff';
        } else if (this.omniShotActive) {
            baseColor = '#ffff00'; // 四面八方射击时变为金色
        }
        
        // 攻击时的特效
        if (this.isAttacking) {
            // 绘制攻击光环
            ctx.save();
            ctx.globalAlpha = 0.6;
            ctx.fillStyle = this.comboCount >= 3 ? '#FF69B4' : this.comboCount >= 2 ? '#FFA500' : '#FFFF00';
            const glowSize = this.meleeRange;
            ctx.fillRect(this.x - (glowSize - this.width) / 2, this.y - (glowSize - this.height) / 2, glowSize, glowSize);
            ctx.restore();
        }
        
        ctx.fillStyle = baseColor;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        
        // 绘制眼睛
        ctx.fillStyle = '#ffff00';
        ctx.fillRect(this.x + 8, this.y + 10, 8, 8);
        ctx.fillRect(this.x + 24, this.y + 10, 8, 8);
        
        // 绘制胸前的计时器
        ctx.fillStyle = '#00ff00';
        ctx.fillRect(this.x + 15, this.y + 25, 10, 10);
        
        // 绘制生命值条
        const healthBarWidth = 40;
        const healthBarHeight = 4;
        const healthPercentage = this.health / this.maxHealth;
        
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(this.x, this.y - 10, healthBarWidth, healthBarHeight);
        ctx.fillStyle = '#00ff00';
        ctx.fillRect(this.x, this.y - 10, healthBarWidth * healthPercentage, healthBarHeight);
        
        // 绘制能量条
        const energyBarWidth = this.width;
        const energyBarHeight = 3;
        const energyPercentage = this.energy / this.maxEnergy;
        
        ctx.fillStyle = '#0000ff';
        ctx.fillRect(this.x, this.y - 15, energyBarWidth, energyBarHeight);
        
        ctx.fillStyle = '#00ffff';
        ctx.fillRect(this.x, this.y - 15, energyBarWidth * energyPercentage, energyBarHeight);
        
        // 绘制连击数
        if (this.comboCount > 1 && this.comboTimer > 0) {
            ctx.save();
            ctx.fillStyle = this.comboCount >= 3 ? '#FF1493' : '#FF6347';
            ctx.font = 'bold 16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(`${this.comboCount}x COMBO!`, this.x + this.width / 2, this.y - 25);
            ctx.restore();
        }
        
        // 攻击效果
        if (this.isAttacking) {
            ctx.fillStyle = 'rgba(255, 255, 0, 0.5)';
            ctx.fillRect(this.x + this.width, this.y, 30, this.height);
        }
    }
}

class Zombie {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 35;
        this.height = 55;
        this.health = 60;
        this.maxHealth = 60;
        this.speed = 25; // 降低移动速度
        this.damage = 15;
        this.points = 100;
        this.lastAttackTime = 0;
        this.attackCooldown = 1500;
        this.shootCooldown = 0;
        this.isRaging = false;
        this.isGiant = false;
        this.hasLostArm = false;
        this.ragingSpeed = 50; // 降低狂暴速度
        this.giantHealth = 150;
        this.giantDamage = 30;
        this.lastTombstoneTime = 0;
        this.tombstoneCooldown = 8000; // 增加到8秒
        this.lastProjectileTime = 0;
        this.projectileCooldown = 2000;
    }
    
    update(deltaTime, ultraman) {
        const dt = deltaTime / 1000;
        
        // 移动向奥特曼
        const dx = ultraman.x - this.x;
        const dy = ultraman.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > 0) {
            const moveSpeed = this.isRaging ? this.ragingSpeed : this.speed;
            this.x += (dx / distance) * moveSpeed * dt;
            this.y += (dy / distance) * moveSpeed * dt;
        }
        
        // 更新冷却时间
        if (this.shootCooldown > 0) {
            this.shootCooldown -= deltaTime;
        }
        
        // 发射墓碑 (降低频率)
        if (Date.now() - this.lastTombstoneTime > this.tombstoneCooldown) {
            this.shootTombstone();
            this.lastTombstoneTime = Date.now();
        }
        
        // 巨型僵尸发射火球和冰球
        if (this.isGiant && Date.now() - this.lastProjectileTime > this.projectileCooldown) {
            this.shootProjectile();
            this.lastProjectileTime = Date.now();
        }
    }
    
    takeDamage(damage) {
        this.health -= damage;
        
        // 检查状态变化
        if (!this.hasLostArm && this.health <= this.maxHealth * 0.6) {
            this.hasLostArm = true;
            this.isRaging = true;
            this.points += 50; // 额外分数
        }
        
        if (!this.isGiant && this.health <= this.maxHealth * 0.2) {
            this.transformToGiant();
        }
    }
    
    transformToGiant() {
        this.isGiant = true;
        this.width = 60;
        this.height = 80;
        this.health = this.giantHealth;
        this.maxHealth = this.giantHealth;
        this.damage = this.giantDamage;
        this.speed = 30; // 巨型僵尸移动较慢
        this.points += 200; // 额外分数
    }
    
    canAttack() {
        return Date.now() - this.lastAttackTime > this.attackCooldown;
    }
    
    shootTombstone() {
        const tombstone = new Tombstone(this.x - 20, this.y + this.height / 2);
        game.addTombstone(tombstone);
    }
    
    shootProjectile() {
        // 随机发射火球或冰球
        if (Math.random() < 0.5) {
            const fireball = new Fireball(this.x - 20, this.y + this.height / 2);
            game.addFireball(fireball);
        } else {
            const iceball = new Iceball(this.x - 20, this.y + this.height / 2);
            game.addIceball(iceball);
        }
    }
    
    render(ctx) {
        // 绘制僵尸
        let color = '#2ecc71';
        if (this.isGiant) {
            color = '#8e44ad';
        } else if (this.isRaging) {
            color = '#e74c3c';
        }
        
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        
        // 绘制眼睛
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(this.x + 8, this.y + 10, 6, 6);
        ctx.fillRect(this.x + this.width - 14, this.y + 10, 6, 6);
        
        // 如果失去手臂，绘制缺失的手臂
        if (this.hasLostArm) {
            ctx.fillStyle = '#34495e';
            ctx.fillRect(this.x + this.width - 8, this.y + 20, 8, 15);
        }
        
        // 绘制生命值条
        const healthBarWidth = this.width;
        const healthBarHeight = 4;
        const healthPercentage = this.health / this.maxHealth;
        
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(this.x, this.y - 10, healthBarWidth, healthBarHeight);
        ctx.fillStyle = '#00ff00';
        ctx.fillRect(this.x, this.y - 10, healthBarWidth * healthPercentage, healthBarHeight);
    }
}

class Beam {
    constructor(x, y, damage, dirX = 1, dirY = 0) {
        this.x = x;
        this.y = y;
        this.width = 30;
        this.height = 5;
        this.speed = 400;
        this.damage = damage;
        this.dirX = dirX; // X方向
        this.dirY = dirY; // Y方向
        
        // 标准化方向向量
        const length = Math.sqrt(dirX * dirX + dirY * dirY);
        if (length > 0) {
            this.dirX = dirX / length;
            this.dirY = dirY / length;
        }
    }
    
    update(deltaTime) {
        const dt = deltaTime / 1000;
        this.x += this.speed * this.dirX * dt;
        this.y += this.speed * this.dirY * dt;
    }
    
    render(ctx) {
        ctx.fillStyle = '#f39c12';
        ctx.fillRect(this.x, this.y, this.width, this.height);
        
        // 光线效果
        ctx.fillStyle = 'rgba(255, 255, 0, 0.5)';
        ctx.fillRect(this.x - 5, this.y - 2, this.width + 10, this.height + 4);
    }
}

class Tombstone {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 25;
        this.height = 40;
        this.speed = 100;
        this.health = 40;
        this.maxHealth = 40;
    }
    
    update(deltaTime) {
        // 只有非地图墓碑才会移动
        if (!this.isMapTombstone) {
            const dt = deltaTime / 1000;
            this.x -= this.speed * dt;
        }
    }
    
    takeDamage(damage) {
        this.health -= damage;
    }
    
    render(ctx) {
        ctx.fillStyle = '#7f8c8d';
        ctx.fillRect(this.x, this.y, this.width, this.height);
        
        // 绘制十字架
        ctx.fillStyle = '#2c3e50';
        ctx.fillRect(this.x + 10, this.y + 5, 5, 20);
        ctx.fillRect(this.x + 5, this.y + 10, 15, 5);
        
        // 绘制生命值条
        const healthBarWidth = this.width;
        const healthBarHeight = 3;
        const healthPercentage = this.health / this.maxHealth;
        
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(this.x, this.y - 8, healthBarWidth, healthBarHeight);
        ctx.fillStyle = '#00ff00';
        ctx.fillRect(this.x, this.y - 8, healthBarWidth * healthPercentage, healthBarHeight);
    }
}

class Fireball {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 15;
        this.height = 15;
        this.speed = 150;
        this.damage = 20;
    }
    
    update(deltaTime) {
        const dt = deltaTime / 1000;
        this.x -= this.speed * dt;
    }
    
    render(ctx) {
        ctx.fillStyle = '#e74c3c';
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, this.y + this.height/2, this.width/2, 0, Math.PI * 2);
        ctx.fill();
        
        // 火焰效果
        ctx.fillStyle = '#f39c12';
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, this.y + this.height/2, this.width/3, 0, Math.PI * 2);
        ctx.fill();
    }
}

class Iceball {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 15;
        this.height = 15;
        this.speed = 150;
        this.damage = 15;
    }
    
    update(deltaTime) {
        const dt = deltaTime / 1000;
        this.x -= this.speed * dt;
    }
    
    render(ctx) {
        ctx.fillStyle = '#3498db';
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, this.y + this.height/2, this.width/2, 0, Math.PI * 2);
        ctx.fill();
        
        // 冰晶效果
        ctx.fillStyle = '#ecf0f1';
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, this.y + this.height/2, this.width/3, 0, Math.PI * 2);
        ctx.fill();
    }
}

class Crystal {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 20;
        this.height = 20;
        this.rotationAngle = 0;
        this.glowIntensity = 0;
        this.glowDirection = 1;
    }
    
    update(deltaTime) {
        const dt = deltaTime / 1000;
        
        // 旋转效果
        this.rotationAngle += 180 * dt; // 每秒旋转180度
        if (this.rotationAngle >= 360) {
            this.rotationAngle -= 360;
        }
        
        // 发光效果
        this.glowIntensity += this.glowDirection * 2 * dt;
        if (this.glowIntensity >= 1) {
            this.glowIntensity = 1;
            this.glowDirection = -1;
        } else if (this.glowIntensity <= 0) {
            this.glowIntensity = 0;
            this.glowDirection = 1;
        }
    }
    
    render(ctx) {
        ctx.save();
        
        // 移动到水晶中心
        ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
        
        // 旋转
        ctx.rotate(this.rotationAngle * Math.PI / 180);
        
        // 绘制发光效果
        const glowSize = 30 + this.glowIntensity * 10;
        const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, glowSize);
        gradient.addColorStop(0, `rgba(0, 255, 255, ${0.8 * this.glowIntensity})`);
        gradient.addColorStop(0.5, `rgba(0, 255, 255, ${0.4 * this.glowIntensity})`);
        gradient.addColorStop(1, 'rgba(0, 255, 255, 0)');
        
        ctx.fillStyle = gradient;
        ctx.fillRect(-glowSize/2, -glowSize/2, glowSize, glowSize);
        
        // 绘制水晶主体
        ctx.fillStyle = '#00ffff';
        ctx.fillRect(-this.width/2, -this.height/2, this.width, this.height);
        
        // 绘制水晶内部光芒
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(-this.width/4, -this.height/4, this.width/2, this.height/2);
        
        // 绘制水晶边框
        ctx.strokeStyle = '#0088cc';
        ctx.lineWidth = 2;
        ctx.strokeRect(-this.width/2, -this.height/2, this.width, this.height);
        
        ctx.restore();
    }
}

class ZombieCannon {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 60;
        this.height = 80;
        this.health = 500; // 僵尸血量的5倍（假设僵尸血量100）
        this.maxHealth = 500;
        this.points = 100; // 击败僵尸大炮的分数
        this.shootTimer = 0;
        this.shootInterval = 10000; // 10秒发射一个僵尸
        this.speed = 80; // 上下移动速度
        this.direction = Math.random() > 0.5 ? 1 : -1; // 随机初始方向
        this.minY = 50; // 最小Y坐标
        this.maxY = 550; // 最大Y坐标
    }
    
    update(deltaTime, game) {
        const dt = deltaTime / 1000;
        
        // 在右边上下移动
        this.y += this.speed * this.direction * dt;
        
        // 碰到边界时反向
        if (this.y <= this.minY || this.y >= this.maxY) {
            this.direction *= -1;
            this.y = Math.max(this.minY, Math.min(this.maxY, this.y));
        }
        
        // 发射僵尸
        this.shootTimer += deltaTime;
        if (this.shootTimer >= this.shootInterval) {
            this.shootZombie(game);
            this.shootTimer = 0;
        }
    }
    
    shootZombie(game) {
        // 在大炮前方生成僵尸
        const zombie = new Zombie(this.x - 50, this.y + this.height / 2 - 30);
        game.addZombie(zombie);
    }
    
    takeDamage(damage) {
        this.health -= damage;
        this.health = Math.max(0, this.health);
    }
    
    render(ctx) {
        // 绘制大炮底座
        ctx.fillStyle = '#654321';
        ctx.fillRect(this.x, this.y + this.height - 30, this.width, 30);
        
        // 绘制大炮主体
        ctx.fillStyle = '#2c3e50';
        ctx.fillRect(this.x + 10, this.y + 20, this.width - 20, this.height - 50);
        
        // 绘制大炮炮管
        ctx.fillStyle = '#34495e';
        ctx.fillRect(this.x - 20, this.y + this.height / 2 - 8, 40, 16);
        
        // 绘制僵尸装饰（表示这是僵尸大炮）
        ctx.fillStyle = '#2ecc71';
        ctx.fillRect(this.x + 20, this.y + 10, 20, 20);
        
        // 绘制红色眼睛
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(this.x + 23, this.y + 13, 4, 4);
        ctx.fillRect(this.x + 33, this.y + 13, 4, 4);
        
        // 绘制生命值条
        const healthBarWidth = this.width;
        const healthBarHeight = 6;
        const healthPercentage = this.health / this.maxHealth;
        
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(this.x, this.y - 15, healthBarWidth, healthBarHeight);
        
        ctx.fillStyle = '#00ff00';
        ctx.fillRect(this.x, this.y - 15, healthBarWidth * healthPercentage, healthBarHeight);
        
        // 绘制发射倒计时指示器
        const shootProgress = this.shootTimer / this.shootInterval;
        ctx.fillStyle = '#ffff00';
        ctx.fillRect(this.x, this.y - 25, this.width * shootProgress, 4);
    }
}

// 启动游戏
let game;
window.addEventListener('load', () => {
    game = new Game();
});